import React from 'react';
import ajax from 'superagent';

import Search from '../../components/search/Search';
import Schedule from '../../components/schedule/Schedule';
import Sort from '../../components/sort/Sort';

class MainAthlete extends React.Component {
    constructor(props) {
        super(props);
        this.displayName = 'MainAthlete';
        this.url = 'api/matches/matchList/get/';

        this.state = {
            data: []
        }
    }

    //  用来 ajax 取数据， 并将数据更新到 state 中 athletsData
    fetchingData(  ) {
        console.log("MainSchedule fetchingData********" );
        this.serverRequest = ajax.get(this.url)
            .end(function(error, response)  {

                if( !error && response ) {
                    let data_origin = response.body.match_list;
                    let data = [];
                    data_origin.map(function( match, index ){
                        data.push({
                            id: match.id,
                            status: match.status,
                            team1: {
                                imgSrc: match.team_1_image,
                                name: match.team_1,
                                score: match.team_1_score,
                            },
                            team2: {
                                imgSrc: match.team_2_image,
                                name: match.team_2,
                                score: match.team_2_score,
                            },
                            location: match.location,
                            time: {
                                date: match.get_start_date,
                                time: match.get_start_time,
                                timeGap: match.get_how_long_day_before_start
                            }
                        })
                    });

                    this.setState({
                        data: data
                    });

                } else {
                    console.error(`Error fetching ${name} `, error);
                }
        }.bind(this));
    }

    componentDidMount() {
        this.fetchingData();
    }

    componentWillUnmount (){
        this.serverRequest.abort();
    }

    render() {
        return (
            <div>
                <Search />
                <Schedule mode="schedule" data={this.state.data} />
            </div>
        );
    }
}

export default MainAthlete;
